import { setStorage } from '@/utils/common'
import { CURRENT_URL } from '@/enums/cacheEnum'
import { useRouter } from 'vue-router'
import { toRefs, defineComponent, h, resolveDynamicComponent } from 'vue'
const SubMenu = defineComponent({
    name: 'SubMenu',
    props: {
        menuInfo: {
            type: Object,
            default: () => ({})
        },
        routerPushKey: {
            type: String,
            default: 'path'
        }
    },
    setup(props) {
        const router = useRouter()
        const { menuInfo, routerPushKey } = toRefs(props)
        function hanldeClickMenu(menu) {
            let path = menu[props.routerPushKey]
            if (import.meta.env.VITE_PUBLIC_PATH && path) {
                if (path.startsWith(import.meta.env.VITE_PUBLIC_PATH.substring(1))) {
                    path = '/' + path
                }
            }
            setStorage(CURRENT_URL, path)
            router.push(path)
        }
        // 渲染icon
        function renderIcon(data) {
            if (data.iconDisplay) {
                if (data.iconType === 'CUSTOM' || data.icon.startsWith('data:image')) {
                    return <img class="anticon icon-style" src={data.icon} />
                }
                const component = resolveDynamicComponent(data.icon) as any
                return h(component)
            }
            return ''
        }
        return () => (
            <aSubMenu
                class={{
                    'submenu-arrow-none': !menuInfo.value.children || !menuInfo.value.children.length
                }}
                key={menuInfo.value.key}
                v-slots={{
                    icon: () => renderIcon(menuInfo.value),
                    title: () => <span>{menuInfo.value.title || menuInfo.value.name}</span>
                }}
            >
                {menuInfo.value.children.map(item => {
                    if (!item.children || !item.children.length) {
                        return (
                            <aMenuItem
                                key={item.key}
                                title={item.title || item.name}
                                value={item.routeName}
                                onClick={() => hanldeClickMenu(item)}
                                v-slots={{
                                    icon: () => renderIcon(item)
                                }}
                            >
                                <span>{item.title || item.name}</span>
                            </aMenuItem>
                        )
                    }
                    return <subMenu key={item.key} menu-info={item} router-push-key={routerPushKey.value} />
                })}
            </aSubMenu>
        )
    }
})
export default SubMenu
